package com.zijiebutiao.controller;

import com.zijiebutiao.dtos.TUserDto;
import com.zijiebutiao.service.TUserService;
import com.zijiebutiao.utils.CodeFactory;
import com.zijiebutiao.utils.JwtUtils;
import com.zijiebutiao.utils.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

/**
 * @Date 2023/2/28 16:12
 * @Author 时间刺客
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@Api(tags = "登录")
public class LoginController {
    @Autowired
    private TUserService tUserService;

    @PostMapping("/dologin")
    @ApiOperation(value = "登录",notes = "用户名(username),密码(password),验证码(code),验证码标识(idcode)必输项",response=Map.class)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="username",value="用户名",required=true,dataType="String"),
//            @ApiImplicitParam(name="password",value="密码",required=true,dataType="String"),
//            @ApiImplicitParam(name="code",value="验证码",required=true,paramType="form",dataType="String"),
//            @ApiImplicitParam(name="idcode",value="验证码标识",required=true,paramType="form",dataType="String")
//    })
    public ResultVo login(@RequestBody TUserDto user){
        ResultVo resultVo=new ResultVo();
        resultVo.setData(false);
        resultVo.setCode(500);
        if (user==null||"".equals(user)){
            resultVo.setErrorMsg("用户名密码验证码不能为空");
            return  resultVo;
        }
        String code= CodeFactory.codesmap.get(user.getIdcode());
        if (code==null||!code.equals(user.getCode())){
            resultVo.setErrorMsg("验证码错误或为空");
            return  resultVo;
        }
        if (!tUserService.login(user)){
            resultVo.setErrorMsg("用户名或者密码错误或为空");
            return  resultVo;
        }
        Map<String,Object> body=new HashMap<>();
        body.put("username",user.getUsername());
        String token=JwtUtils.createToken(body,60);

        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("username",user.getUsername());

        resultVo.setData(map);
        resultVo.setCode(200);

        return resultVo;
    }
}
